package com.aiju.cash.ui.enter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aiju.app.DataProviderManager;
import com.aiju.app.SimpleHttpCallback;
import com.aiju.app.config.ConfigManager;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.cash.core.api.EnterApi;
import com.aiju.cash.core.event.ShopListChangeEven;
import com.aiju.cash.ui.enter.entity.EnterShopInfo;
import com.aiju.cash.ui.enter.util.CityData;
import com.aiju.cash.util.GsonHelper;
import com.aiju.common.event.EventCenter;
import com.aiju.forexpand.addresspicker.AddressPicker;
import com.aiju.utils.CheckUtil;
import com.aiju.utils.L;
import com.aiju.utils.PreferencesUtils;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.dialog.MemberDialog;
import com.aiju.widgit.layout.SettingItemEditView;
import com.aiju.widgit.layout.SettingItemTextView;

/**
 * @author: 佐为
 * @date: 2017-05-25 14:47
 * @version: V1.0
 * @Description: 入驻口碑
 */
public class CheckInActivity extends BaseTitleActivity implements View.OnClickListener {

    public static final int LOGO = 101;//logo
    public static final int HOME = 102;//首图
    public static final int HEADER = 103;//门头照
    public static final int PERMIT = 104;//营业执照
    public static final int ADDRESS = 105;//门店地址
    public static final int AUTH = 106;//授权函
    public static final int MNAGER = 107;//经营许可证
    public static final int OHTER = 108;//其他证明
    public static final int OHTER_1 = 109;//其他营业信息


    private SettingItemEditView storeNameEditView, subbranchNameEditView,
            storePhoneEditView, brandNameEditView;

    private SettingItemTextView categoryTextView, addressTextView,
            homeImageTextView, headeImageTextView, permitImageTextView;

    //必须
    private String storeName = "", storePhone = "", storeCategory = "";//店名，电话，品类code
    private String home = "", header = "", permit = "";//图片id: 首图，门头照，营业执照
    private String province_code = "", city_code = "", district_code = "";//地址code
    private String longitude = "", latitude = "";//高德坐标

    //可选
    private String logo = "", auth = "", manager = "", other = "";//图片id: logo，授权函,经营许可，其他证明
    private String branch_shop_name = "", brand_name = "", address = ""; //分店名，品牌名，详细地址
    private String category_name = "", code_name = "";//字符：品类，省市县
    private String licence_code = "", licence_name = "", business_certificate_expires = "";//营业执照code,注册号，名称,有效期
    private String wifi = "", parking = "", no_smoking = "", box = "", avg_price = "0.00";
    private String licence_expires = ""; //营业执照过期时间

    private String shopType, store_id, id;
    private EnterShopInfo enterShopInfo;

    private int sava;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_in);
        setCenterTitle("入驻口碑");

        sava = getIntent().getIntExtra("sava", -1);
        shopType = getIntent().getStringExtra("shopType");
        shopType = !TextUtils.isEmpty(shopType) && shopType.equals("直营店") ? "1" : "2";
        enterShopInfo = (EnterShopInfo) getIntent().getSerializableExtra("enterShopInfo");

        storeNameEditView = (SettingItemEditView) findViewById(R.id.set_store_name);
        storeNameEditView.getleftView().setText(Html.fromHtml("门店名称<font color='#ec4545'>*</font>"));
        storeNameEditView.getRightView().setHint("例：汉堡王");
        storeNameEditView.getRightView().setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)});
        storeNameEditView.setEditable(true);

        subbranchNameEditView = (SettingItemEditView) findViewById(R.id.set_subbranch__name);
        subbranchNameEditView.getRightView().setHint("例：杭州下沙物美店");
        subbranchNameEditView.getRightView().setFilters(new InputFilter[]{new InputFilter.LengthFilter(25)});
        subbranchNameEditView.setEditable(true);

        storePhoneEditView = (SettingItemEditView) findViewById(R.id.set_store_phone);
        storePhoneEditView.getRightView().setHint("填写多个请以“ , ”隔开");
        storePhoneEditView.getleftView().setText(Html.fromHtml("门店电话<font color='#ec4545'>*</font>"));
        storePhoneEditView.setEditable(true);

        brandNameEditView = (SettingItemEditView) findViewById(R.id.set_brand_name);
        brandNameEditView.getRightView().setHint("选填，不填写则默认为“其他品牌”");
        brandNameEditView.setEditable(true);

        addressTextView = (SettingItemTextView) findViewById(R.id.set_store_adress);
        addressTextView.getleftView().setText(Html.fromHtml("门店地址<font color='#ec4545'>*</font>"));
        homeImageTextView = (SettingItemTextView) findViewById(R.id.set_store_home);
        homeImageTextView.getleftView().setText(Html.fromHtml("门店首图<font color='#ec4545'>*</font>"));
        headeImageTextView = (SettingItemTextView) findViewById(R.id.set_store_header);
        headeImageTextView.getleftView().setText(Html.fromHtml("门头照与内景图<font color='#ec4545'>*</font>"));
        permitImageTextView = (SettingItemTextView) findViewById(R.id.set_store_permit);
        permitImageTextView.getleftView().setText(Html.fromHtml("营业执照<font color='#ec4545'>*</font>"));
        categoryTextView = (SettingItemTextView) findViewById(R.id.set_store_category);
        categoryTextView.getleftView().setText(Html.fromHtml("营业品类<font color='#ec4545'>*</font>"));

        ((TextView) findViewById(R.id.tv_name_desc)).setText(Html.fromHtml(getString(R.string.name_desc)));
        ((TextView) findViewById(R.id.tv_brand_desc)).setText(Html.fromHtml(getString(R.string.phone_desc)));
        findViewById(R.id.set_store_category).setOnClickListener(this);
        findViewById(R.id.set_store_logo).setOnClickListener(this);
        findViewById(R.id.set_store_home).setOnClickListener(this);
        findViewById(R.id.set_store_header).setOnClickListener(this);
        findViewById(R.id.set_store_permit).setOnClickListener(this);
        findViewById(R.id.set_store_auth).setOnClickListener(this);
        findViewById(R.id.set_store_adress).setOnClickListener(this);
        findViewById(R.id.set_store_qita).setOnClickListener(this);
        findViewById(R.id.set_store_manage).setOnClickListener(this);
        findViewById(R.id.set_store_qita1).setOnClickListener(this);

        findViewById(R.id.btn_check_in).setOnClickListener(this);
        setInfo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.set_store_category://经营品类
                showCategoryDialog();
                break;
            case R.id.set_store_logo://品牌Logo
                startImageActivity(LogoImageActivity.class, logo, LOGO);
                break;
            case R.id.set_store_home://门店首页
                startImageActivity(HomeImageActivity.class, home, HOME);
                break;
            case R.id.set_store_header://门头照与内景图
                startImageActivity(HeaderImageActivity.class, header, HEADER);
                break;
            case R.id.set_store_permit://营业执照
                startImageActivity(PermitImageActivity.class, permit, PERMIT);
                break;
            case R.id.set_store_auth://授权函
                startImageActivity(AuthImageActivity.class, auth, AUTH);
                break;
            case R.id.set_store_manage://经营管理
                Intent intent2 = new Intent(this, ManageImageActivity.class);
                intent2.putExtra("licence_expires", licence_expires);
                intent2.putExtra("image_id", manager);
                startActivityForResult(intent2, MNAGER);
                break;
            case R.id.set_store_qita://其他证明
                startImageActivity(OtherImageActivity.class, other, OHTER);
                break;
            case R.id.set_store_qita1://其他营业信息
                Intent intent = new Intent(this, OtherManageActivity.class);
                intent.putExtra("wifi", wifi);
                intent.putExtra("parking", parking);
                intent.putExtra("no_smoking", no_smoking);
                intent.putExtra("box", box);
                intent.putExtra("avg_price", avg_price);
                startActivityForResult(intent, OHTER_1);
                break;
            case R.id.set_store_adress://地址
                Intent intentAdress = new Intent(this, AdressActivity.class);
                intentAdress.putExtra("codeName", code_name);
                intentAdress.putExtra("province_code", province_code);
                intentAdress.putExtra("city_code", city_code);
                intentAdress.putExtra("district_code", district_code);
                intentAdress.putExtra("address", address);
                intentAdress.putExtra("longitude", longitude);
                intentAdress.putExtra("latitude", latitude);
                startActivityForResult(intentAdress, ADDRESS);
                break;
            case R.id.btn_check_in:
                checkIn();
                break;
        }
    }

    /**
     * 跳转选择图片界面
     */
    private void startImageActivity(Class<? extends Activity> clas, String imageId, int requestCode) {
        Intent intent = new Intent(this, clas);
        intent.putExtra("image_id", imageId);
        if (clas == PermitImageActivity.class) {
            intent.putExtra("licence_code", licence_code);
            intent.putExtra("licence_name", licence_name);
            intent.putExtra("business_certificate_expires", business_certificate_expires);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 上传资料
     */
    private void checkIn() {
        storeName = storeNameEditView.getRightString();
        if (TextUtils.isEmpty(storeName)) {
            T.ToastShort("请输入门店名称");
            return;
        }
        if (!CheckUtil.checkNickName(storeName)) {
            T.ToastShort("门店名称仅支持不超过15个字符的汉字、数字、英文及下划线");
            return;
        }

        if (TextUtils.isEmpty(code_name)) {
            T.ToastShort("请输入门店地址");
            return;
        }
        storePhone = storePhoneEditView.getRightString();
        branch_shop_name = subbranchNameEditView.getRightString();
        if (TextUtils.isEmpty(storePhone)) {
            T.ToastShort("请输入门店电话");
            return;
        }
        if (!CheckUtil.isMultiplePhone(storePhone)) {
            return;
        }

        if (TextUtils.isEmpty(storeCategory)) {
            T.ToastShort("请选择营业品类");
            return;
        }
        if (TextUtils.isEmpty(home)) {
            T.ToastShort("请上传门店首图");
            return;
        }
        if (TextUtils.isEmpty(header)) {
            T.ToastShort("请上传门头照与内景图");
            return;
        }
        if (TextUtils.isEmpty(permit)) {
            T.ToastShort("请上传营业执照");
            return;
        }

        new MemberDialog(this)
                .setTitileText("确认上传？")
                .setMsgText("资料上传后需要一个工作日左右审核完成，期间不能修改上传的资料")
                .setLeftText("返回修改")
                .setRightText("确认提交")
                .setLayoutParams()
                .setOnSimpleClick(new MemberDialog.OnSimpleClick() {
                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onSubmit() {
                        createAndUpdateShop();
                    }
                })
                .show();
    }

    /**
     * 上传口碑资料
     */
    private void createAndUpdateShop() {
        new EnterApi(mDialogHelper).createAndUpdateShop(id, store_id, shopType,
                storeCategory, brand_name, logo, storeName, branch_shop_name, province_code, city_code,
                district_code, address, code_name, category_name, longitude, latitude, storePhone, home, header, wifi, parking,
                avg_price, permit, licence_code, licence_name, manager, business_certificate_expires,
                auth, no_smoking, box, other, licence_expires, new SimpleHttpCallback() {
                    @Override
                    protected void onDataSuccess(String data) {
                        //删除本地缓存
                        EnterShopInfo enterShopInfo = GsonHelper.convertEntity(data, EnterShopInfo.class);
                        if (!TextUtils.isEmpty(enterShopInfo.getSub_msg())) {
                            T.ToastShort(enterShopInfo.getSub_msg());
                        }
                        EventCenter.getInstance().post(new ShopListChangeEven());//更新店铺列表
                        PreferencesUtils.putString(DataProviderManager.getContext(), "", ConfigManager.getInstance().getUser().getPhone());
                        Intent intent = new Intent(CheckInActivity.this, EnterInfoActivity.class);
                        intent.putExtra("shop", enterShopInfo);
                        startActivity(intent);
                        finish();
                    }
                }
        );

    }

    /**
     * 显示品类
     */
    private void showCategoryDialog() {
        CityData.showCategoryDialog(this, new AddressPicker.OnChangeCity() {
            @Override
            public void onChangeCity(String province, String city, String area) {
                storeCategory = TextUtils.isEmpty(area) ? CityData.getCode(city) : CityData.getCode(area);
                L.d("类别编号： " + storeCategory);
                category_name = CityData.getAllAddress(province, city, area);
                L.d("类别全拼： " + category_name);
                categoryTextView.getRightView().setTextColor(Util.getColor(R.color.app_text_color));
                categoryTextView.getRightView().setText(category_name);
            }
        });
    }

    /**
     * 设置显示信息
     */
    private void setInfo() {
        if (enterShopInfo != null) {
            //店铺名
            if (!TextUtils.isEmpty(enterShopInfo.getMain_shop_name())) {
                storeName = enterShopInfo.getMain_shop_name();
                storeNameEditView.setRightText(storeName);
                EditText rightView = (EditText) storeNameEditView.getRightView();
                rightView.setSelection(storeName.length());
            }
            //分店名
            if (!TextUtils.isEmpty(enterShopInfo.getBranch_shop_name())) {
                branch_shop_name = enterShopInfo.getBranch_shop_name();
                subbranchNameEditView.setRightText(branch_shop_name);
                EditText rightView = (EditText) subbranchNameEditView.getRightView();
                rightView.setSelection(branch_shop_name.length());
            }
            //门店电话
            if (!TextUtils.isEmpty(enterShopInfo.getContact_number())) {
                storePhone = enterShopInfo.getContact_number();
                storePhoneEditView.setRightText(storePhone);
                EditText rightView = (EditText) storePhoneEditView.getRightView();
                rightView.setSelection(storePhone.length());
            }
            //品类
            if (!TextUtils.isEmpty(enterShopInfo.getCategory_id())) {
                categoryTextView.getRightView().setTextColor(Util.getColor(R.color.app_text_color));
                categoryTextView.setRightText(enterShopInfo.getCategory_name());
                category_name = enterShopInfo.getCategory_name();
                storeCategory = enterShopInfo.getCategory_id();
            }
            //门店地址
            if (!TextUtils.isEmpty(enterShopInfo.getCode_name())) {
                code_name = enterShopInfo.getCode_name();
                addressTextView.getRightView().setTextColor(Util.getColor(R.color.app_text_color));
                if (!TextUtils.isEmpty(enterShopInfo.getAddress())) {
                    address = enterShopInfo.getAddress();
                    addressTextView.setRightText(enterShopInfo.getCode_name() + enterShopInfo.getAddress());
                } else {
                    addressTextView.setRightText(enterShopInfo.getCode_name());
                }
            }
            //品牌名称
            if (!TextUtils.isEmpty(enterShopInfo.getBrand_name())) {
                brand_name = enterShopInfo.getBrand_name();
                brandNameEditView.getRightView().setTextColor(Util.getColor(R.color.app_text_color));
                brandNameEditView.setRightText(enterShopInfo.getBrand_name());
            }
            //品牌logo
            if (!TextUtils.isEmpty(enterShopInfo.getBrand_logo())) {
                logo = enterShopInfo.getBrand_logo();
                ((SettingItemTextView) findViewById(R.id.set_store_logo)).setRightText("已上传");
            }
            //首图
            if (!TextUtils.isEmpty(enterShopInfo.getMain_image())) {
                home = enterShopInfo.getMain_image();
                ((SettingItemTextView) findViewById(R.id.set_store_home)).setRightText("已上传");
            }
            //门头照
            if (!TextUtils.isEmpty(enterShopInfo.getAudit_images())) {
                header = enterShopInfo.getAudit_images();
                ((SettingItemTextView) findViewById(R.id.set_store_header)).setRightText("已上传");
            }
            //营业执照
            if (!TextUtils.isEmpty(enterShopInfo.getLicence())) {
                permit = enterShopInfo.getLicence();
                ((SettingItemTextView) findViewById(R.id.set_store_permit)).setRightText("已上传");
            }
            //授权函
            if (!TextUtils.isEmpty(enterShopInfo.getAuth_letter())) {
                auth = enterShopInfo.getAuth_letter();
                ((SettingItemTextView) findViewById(R.id.set_store_auth)).setRightText("已上传");
            }
            //经营许可证
            if (!TextUtils.isEmpty(enterShopInfo.getBusiness_certificate())) {
                manager = enterShopInfo.getBusiness_certificate();
                ((SettingItemTextView) findViewById(R.id.set_store_manage)).setRightText("已上传");
            }
            //其他证明
            if (!TextUtils.isEmpty(enterShopInfo.getBusiness_certificate())) {
                other = enterShopInfo.getOther_authorization();
                ((SettingItemTextView) findViewById(R.id.set_store_qita)).setRightText("已上传");
            }
            //地址code
            province_code = enterShopInfo.getProvince_code();
            city_code = enterShopInfo.getCity_code();
            district_code = enterShopInfo.getDistrict_code();

            //营业执照相关信息
            licence_code = enterShopInfo.getLicence_code();
            licence_name = enterShopInfo.getLicence_name();
            business_certificate_expires = enterShopInfo.getBusiness_certificate_expires();

            //其他营业信息
            wifi = enterShopInfo.getWifi();
            parking = enterShopInfo.getParking();
            no_smoking = enterShopInfo.getNo_smoking();
            box = enterShopInfo.getBox();
            avg_price = enterShopInfo.getAvg_price();

            //坐标
            latitude = enterShopInfo.getLatitude();
            longitude = enterShopInfo.getLongitude();

            //店铺类型
            shopType = enterShopInfo.getShop_type();
            id = enterShopInfo.getId();
            store_id = enterShopInfo.getStore_id();
            //营业执照过期时间
            licence_expires = enterShopInfo.getLicence_expires();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (sava != 1) {
            return;
        }
        EnterShopInfo enterShopInfo = new EnterShopInfo();
        enterShopInfo.setMain_shop_name(storeNameEditView.getRightText());
        enterShopInfo.setBranch_shop_name(subbranchNameEditView.getRightText());
        enterShopInfo.setCategory_id(storeCategory);
        enterShopInfo.setContact_number(storePhoneEditView.getRightText());
        enterShopInfo.setBrand_name(brandNameEditView.getRightText());
        enterShopInfo.setAddress(address);
        enterShopInfo.setReview_status("3");

        //添加字段
        enterShopInfo.setCategory_name(category_name);
        enterShopInfo.setCode_name(code_name);

        //图片
        enterShopInfo.setBrand_logo(logo);//logo
        enterShopInfo.setMain_image(home);//首图
        enterShopInfo.setAudit_images(header);//门头
        enterShopInfo.setLicence(permit);//营业执照
        enterShopInfo.setAuth_letter(auth); //授权函
        enterShopInfo.setOther_authorization(other); //其他证明
        enterShopInfo.setBusiness_certificate(manager);//经营许可

        //城市 营业信息
        enterShopInfo.setProvince_code(province_code);
        enterShopInfo.setCity_code(city_code);
        enterShopInfo.setDistrict_code(district_code);
        enterShopInfo.setLicence_code(licence_code);
        enterShopInfo.setLicence_name(licence_name);
        enterShopInfo.setBusiness_certificate_expires(business_certificate_expires);

        enterShopInfo.setWifi(wifi);
        enterShopInfo.setParking(parking);
        enterShopInfo.setBox(box);
        enterShopInfo.setNo_smoking(no_smoking);
        enterShopInfo.setAvg_price(avg_price);

        enterShopInfo.setLatitude(latitude);
        enterShopInfo.setLongitude(longitude);
        enterShopInfo.setShop_type(shopType);

        enterShopInfo.setLicence_expires(licence_expires);
        String jsonStr = GsonHelper.object2JsonStr(enterShopInfo);
        String storeId = ConfigManager.getInstance().getUser().getPhone();
        PreferencesUtils.putString(this, storeId, jsonStr);
        EventCenter.getInstance().post(new ShopListChangeEven());//更新店铺列表
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        switch (requestCode) {
            case LOGO:
                logo = data.getStringExtra("data");
                ((SettingItemTextView) findViewById(R.id.set_store_logo)).setRightText(TextUtils.isEmpty(logo) ? "请上传" : "已上传");
                L.d("品牌logo：" + logo);
                break;
            case HEADER:
                header = data.getStringExtra("data");
                ((SettingItemTextView) findViewById(R.id.set_store_header)).setRightText(TextUtils.isEmpty(header) ? "请上传" : "已上传");
                L.d("门头照：" + header);
                break;
            case HOME:
                home = data.getStringExtra("data");
                ((SettingItemTextView) findViewById(R.id.set_store_home)).setRightText(TextUtils.isEmpty(home) ? "请上传" : "已上传");
                L.d("门店首图：" + home);
                break;
            case PERMIT:
                permit = data.getStringExtra("data");
                licence_name = data.getStringExtra("licence_name");
                licence_code = data.getStringExtra("licence_code");
                business_certificate_expires = data.getStringExtra("business_certificate_expires");
                ((SettingItemTextView) findViewById(R.id.set_store_permit)).setRightText(TextUtils.isEmpty(permit) ? "请上传" : "已上传");
                L.d("营业执照：" + permit + licence_name + licence_code + business_certificate_expires);
                break;
            case OHTER:
                other = data.getStringExtra("data");
                ((SettingItemTextView) findViewById(R.id.set_store_qita)).setRightText(TextUtils.isEmpty(other) ? "请上传" : "已上传");
                L.d("其他证明：" + other);
                break;
            case OHTER_1:
                wifi = data.getStringExtra("wifi");
                parking = data.getStringExtra("parking");
                no_smoking = data.getStringExtra("no_smoking");
                box = data.getStringExtra("box");
                avg_price = data.getStringExtra("avg_price");
                L.d("其他营业信息：" + wifi + parking + no_smoking + box + avg_price);
                break;
            case AUTH:
                auth = data.getStringExtra("data");
                ((SettingItemTextView) findViewById(R.id.set_store_auth)).setRightText(TextUtils.isEmpty(auth) ? "请上传" : "已上传");
                L.d("授权函：" + auth);
                break;
            case MNAGER:
                manager = data.getStringExtra("data");
                licence_expires = data.getStringExtra("licence_expires");
                ((SettingItemTextView) findViewById(R.id.set_store_manage)).setRightText(TextUtils.isEmpty(manager) ? "请上传" : "已上传");
                L.d("经营许可证：" + manager + licence_expires);
                break;
            case ADDRESS:
                code_name = data.getStringExtra("codeName");
                address = data.getStringExtra("address");
                addressTextView.getRightView().setTextColor(Util.getColor(R.color.app_text_color));
                addressTextView.setRightText(code_name + address);

                longitude = data.getStringExtra("longitude");
                latitude = data.getStringExtra("latitude");
                province_code = data.getStringExtra("province_code");
                city_code = data.getStringExtra("city_code");
                district_code = data.getStringExtra("district_code");

                L.d("地址：" + latitude + longitude + code_name + address + province_code + city_code + district_code);
                break;
            case 1:
                break;
        }
    }
}
